package com.fractalist.man.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fractalist.base.cache.Cache;
import com.fractalist.base.core.constants.SystemConstants;
import com.fractalist.base.core.decode.Base64;
import com.fractalist.base.core.model.JsonErrorResponse;
import com.fractalist.base.core.model.JsonSuccessResponse;
import com.fractalist.base.core.utils.MyDateUtils;
import com.fractalist.base.core.web.BaseActionSupport;
import com.fractalist.man.base.ManConstants;
import com.fractalist.man.base.SqlUtils;
import com.fractalist.man.service.IAlbumsImageService;
import com.fractalist.man.service.IAlbumsService;
import com.fractalist.man.service.IAnswerService;
import com.fractalist.man.service.IArticleCollectionService;
import com.fractalist.man.service.IArticleService;
import com.fractalist.man.service.ICommentService;
import com.fractalist.man.service.IFilterService;
import com.fractalist.man.service.IFmService;
import com.fractalist.man.service.IQuestionService;
import com.fractalist.man.service.ISplashScreenService;
import com.fractalist.man.service.IUserAttentionService;
import com.fractalist.man.service.IUserService;
import com.fractalist.man.service.IVersionService;

@Controller
@Scope("prototype")
@ParentPackage("default")
public class UserAction extends BaseActionSupport {

	private static final long serialVersionUID = -2111808911345170917L;

	private static final Logger logger = Logger.getLogger("R");

	@Autowired
	private ISplashScreenService splashScreenService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IAlbumsService albumsService;
	@Autowired
	private IAlbumsImageService albumsImageService;
	@Autowired
	private IArticleService articleService;
	@Autowired
	private IUserAttentionService userAttentionService;
	@Autowired
	private IFmService fmService;
	@Autowired
	private IArticleCollectionService articleCollectionService;
	@Autowired
	private ICommentService commentService;
	@Autowired
	private IFilterService filterService;
	@Autowired
	private IQuestionService questionService;
	@Autowired
	private IAnswerService answerService;
	@Autowired
	private IVersionService versionService;

	private Map<String, Object> paramMap;

	private String expire = "5mn";

	private String passport;
	private String password;

	private Long userId;
	private String name;
	private Integer gender;
	private Integer age;
	private String bwh;
	private String constellation;

	private String phoneNumber;
	private String platform;

	private Integer pageNumber = 1;
	private Integer pageLine = ManConstants.COMMON_PAGE_SIZE;
	private Integer state;

	private String image;
	private String fomart;
	private String[] images;

	private Long albumId;
	private String summary;

	private Long followUserId;
	private Boolean value;

	private Long columnId;

	private Long articleId;
	private String content;

	private Long questionId;

	/**
	 * 获取应用最新版本号
	 */
	@Action(value = "/getLastVersion", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getLastVersion() {
		Map<String, Object> version = versionService
				.queryOneRowFromDbOrCache(
						"select * from man_base_version order by create_time desc limit 0,1",
						expire);
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("version", version.get("version"));
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 获取树洞回答
	 */
	@Action(value = "/gets", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String gets() {
		if (pageNumber < 1) {
			pageNumber = 1;
		}
		if (pageLine < 0) {
			pageLine = ManConstants.COMMON_PAGE_SIZE;
		}
		if (questionId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-111");
			jsonErrorResponse.setErrorMessage("抱歉，问题id为空");
			return renderJson(jsonErrorResponse);
		}
		List<Map<String, Object>> answerList = answerService
				.queryListFromDbOrCache(
						"select * from man_base_answer where questionId = "
								+ questionId
								+ " order by createDate desc limit "
								+ ((pageNumber - 1) * pageLine) + ","
								+ pageLine, expire);
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("answers", answerList);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 获取树洞问题
	 */
	@Action(value = "/getQuestions", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getQuestions() {
		if (pageNumber < 1) {
			pageNumber = 1;
		}
		if (pageLine < 0) {
			pageLine = ManConstants.COMMON_PAGE_SIZE;
		}
		List<Map<String, Object>> questionList = questionService
				.queryListFromDbOrCache(
						"select * from man_base_question order by createDate desc limit "
								+ ((pageNumber - 1) * pageLine) + ","
								+ pageLine, expire);
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("questions", questionList);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 获取装女郎匹配组
	 */
	@Action(value = "/getGirlPK", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getGirlPK() {
		List<Map<String, Object>> tmpList = null;
		List<Map<String, Object>> girlPkList = new ArrayList<Map<String, Object>>();
		if (ManConstants.GIRL_PK_LIST == null
				|| ManConstants.GIRL_PK_LIST.size() < 2) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			// paramMap.put("user_type", ManConstants.USER_TYPE_REG);
			paramMap.put("state", ManConstants.USER_STATE_COMMON);
			paramMap.put("gender", ManConstants.USER_GENDER_FEMALE);
			List<Map<String, Object>> cacheTmpList = userService
					.queryListFromDbOrCache(SqlUtils.genderQuerySql(
							"man_base_user",
							SqlUtils.genderConditionsByType(paramMap, "and")),
							expire);
			if (tmpList == null) {
				tmpList = new ArrayList<Map<String, Object>>();
			}
			for (int i = 0; i < cacheTmpList.size(); i++) {
				tmpList.add(cacheTmpList.get(i));
			}
			for (int i = 0; i < tmpList.size(); i++) {
				Map<String, Object> user = tmpList.get(i);
				Long userIdTmp = (Long) user.get("id");
				List<Map<String, Object>> albumsList = albumsService
						.queryListFromDbOrCache(SqlUtils.genderQuerySql(
								"man_base_albums", "user_id = " + userIdTmp),
								expire);
				user.put("albums", albumsList);
				for (Map<String, Object> albums : albumsList) {
					Long albumsId = (Long) albums.get("id");
					List<Map<String, Object>> albumsImagesList = albumsImageService
							.queryListFromDbOrCache(SqlUtils.genderQuerySql(
									"man_base_albums_image", "albumId = "
											+ albumsId + " and userId = "
											+ userIdTmp), expire);
					albums.put("images", albumsImagesList);
				}
			}
		}
		if (ManConstants.GIRL_PK_LIST != null
				&& ManConstants.GIRL_PK_LIST.size() == 1) {
			addGirlPk(tmpList, girlPkList, 0);
		}
		if (ManConstants.GIRL_PK_LIST == null
				|| ManConstants.GIRL_PK_LIST.size() == 0) {
			ManConstants.GIRL_PK_LIST = tmpList;
		}
		int maxPkCount = 2;
		int girlPkListSize = girlPkList.size();
		for (int i = 0; i < maxPkCount - girlPkListSize; i++) {
			int index = new Double(Math.random()
					* ManConstants.GIRL_PK_LIST.size()).intValue();
			addGirlPk(tmpList, girlPkList, index);
		}
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("girls", girlPkList);
		return renderJson(jsonSuccessResponse);
	}

	private void addGirlPk(List<Map<String, Object>> tmpList,
			List<Map<String, Object>> girlPkList, int index) {
		synchronized (ManConstants.GIRL_PK_LIST) {
			girlPkList.add(ManConstants.GIRL_PK_LIST.get(index));
			ManConstants.GIRL_PK_LIST.remove(index);
		}
	}

	/**
	 * 获取评论
	 */
	@Action(value = "/comment", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String comment() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-101");
			jsonErrorResponse.setErrorMessage("抱歉，用户id为空");
			return renderJson(jsonErrorResponse);
		}
		if (articleId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-102");
			jsonErrorResponse.setErrorMessage("抱歉，文章id为空");
			return renderJson(jsonErrorResponse);
		}
		if (StringUtils.isEmpty(content)) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-103");
			jsonErrorResponse.setErrorMessage("抱歉，评论内容不能为空");
			return renderJson(jsonErrorResponse);
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		paramMap.put("articleId", articleId);
		paramMap.put("content", content);
		paramMap.put("state", ManConstants.COMMENT_STATE_COMMON);
		paramMap.put("crateDate",
				MyDateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss"));
		String key = "filter_str_group";
		if (Cache.get(key) == null) {
			synchronized (ManConstants.FIILTER_KEY_STR) {
				List<Map<String, Object>> filterList = filterService
						.queryListFromDbOrCache(
								"select * from man_base_filter", expire);
				if (filterList != null && filterList.size() > 0) {
					StringBuilder stringBuilder = new StringBuilder();
					for (int i = 0; i < filterList.size(); i++) {
						stringBuilder.append(filterList.get(i).get("keystr")
								+ "|");
					}
					stringBuilder.deleteCharAt(stringBuilder.length() - 1);
					ManConstants.FIILTER_KEY_STR = stringBuilder.toString();
				}
				Cache.add(key, ManConstants.FIILTER_KEY_STR, expire);
			}
		}
		if (ManConstants.FIILTER_KEY_STR == null) {
			ManConstants.FIILTER_KEY_STR = "";
		}
		Pattern pattern = Pattern.compile(ManConstants.FIILTER_KEY_STR);
		Matcher m = pattern.matcher(content);
		if (m.matches()) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-104");
			jsonErrorResponse.setErrorMessage("抱歉，评论内容存在敏感字，请重新编辑");
			return renderJson(jsonErrorResponse);
		}
		Long commentIdTmp = commentService.add(SqlUtils.genderInsertSql(
				"man_base_comment", paramMap));
		if (commentIdTmp > 0) {
			JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
			return renderJson(jsonSuccessResponse);
		} else {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-105");
			jsonErrorResponse.setErrorMessage("抱歉，评论出现异常，评论失败");
			return renderJson(jsonErrorResponse);
		}
	}

	/**
	 * 获取评论
	 */
	@Action(value = "/getComment", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getComment() {
		if (pageNumber < 1) {
			pageNumber = 1;
		}
		if (pageLine < 0) {
			pageLine = ManConstants.COMMON_PAGE_SIZE;
		}
		if (articleId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-92");
			jsonErrorResponse.setErrorMessage("抱歉，文章id为空");
			return renderJson(jsonErrorResponse);
		}
		List<Map<String, Object>> commentList = commentService
				.queryListFromDbOrCache(
						"select c.*,u.`name` from man_base_comment c , man_base_user u where c.userId = u.id and c.articleId = "
								+ articleId
								+ "  order by c.crateDate desc limit "
								+ ((pageNumber - 1) * pageLine)
								+ ","
								+ pageLine, expire);
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("articles", commentList);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 收藏/取消收藏文章
	 */
	@Action(value = "/favorite", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String favorite() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-81");
			jsonErrorResponse.setErrorMessage("抱歉，用户id为空");
			return renderJson(jsonErrorResponse);
		}
		if (articleId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-82");
			jsonErrorResponse.setErrorMessage("抱歉，被收藏、取消收藏文章id为空");
			return renderJson(jsonErrorResponse);
		}
		if (value == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-83");
			jsonErrorResponse.setErrorMessage("抱歉，是否收藏选项不能为空");
			return renderJson(jsonErrorResponse);
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		paramMap.put("articleId", articleId);
		if (value) {
			paramMap.put("create_time",
					MyDateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss"));
			articleCollectionService.add(SqlUtils.genderInsertSql(
					"man_base_article_collection", paramMap));
		} else {
			articleCollectionService
					.excute("delete from man_base_article_collection where userId = "
							+ userId + " and articleId = " + articleId);
		}
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 获取文章
	 */
	@Action(value = "/getArticle", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getArticle() {
		if (pageNumber < 1) {
			pageNumber = 1;
		}
		if (pageLine < 0) {
			pageLine = ManConstants.COMMON_PAGE_SIZE;
		}
		List<Map<String, Object>> artileList = articleService
				.queryListFromDbOrCache(
						"select a.*,u.`name` from man_base_article a,man_base_user u where a.author_id = u.id and a.columnId = "
								+ columnId
								+ " or a.author_id in (select b.followUserId from man_base_user_attention b where b.userId = "
								+ userId
								+ " and b.userId = u.id) order by a.top_time desc,a.create_time desc limit "
								+ ((pageNumber - 1) * pageLine)
								+ ","
								+ pageLine, expire);
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("articles", artileList);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 获取尤物
	 */
	@Action(value = "/getStunner", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getStunner() {
		if (pageNumber < 1) {
			pageNumber = 1;
		}
		if (pageLine < 0) {
			pageLine = ManConstants.COMMON_PAGE_SIZE;
		}
		String key = "getStunner_" + pageNumber + "_" + pageLine;
		List<Map<String, Object>> stunnerList = (List<Map<String, Object>>) Cache
				.get(key);
		if (stunnerList == null) {
			String sql = "select * from man_base_user where state = "
					+ ManConstants.USER_STATE_COMMON + " and gender = "
					+ ManConstants.USER_GENDER_FEMALE
					+ " order by create_time desc limit "
					+ ((pageNumber - 1) * pageLine) + "," + pageLine;
			stunnerList = userService.queryList(sql);
			if (stunnerList != null && stunnerList.size() > 0) {
				for (int i = 0; i < stunnerList.size(); i++) {
					Map<String, Object> user = stunnerList.get(i);
					Long userIdTmp = (Long) user.get("id");
					List<Map<String, Object>> albumsList = albumsService
							.queryList(SqlUtils
									.genderQuerySql("man_base_albums",
											"user_id = " + userIdTmp));
					user.put("albums", albumsList);
					for (Map<String, Object> albums : albumsList) {
						Long albumsId = (Long) albums.get("id");
						List<Map<String, Object>> albumsImagesList = albumsImageService
								.queryList(SqlUtils.genderQuerySql(
										"man_base_albums_image", "albumId = "
												+ albumsId + " and userId = "
												+ userIdTmp));
						albums.put("images", albumsImagesList);
					}
				}
				Cache.add(key, stunnerList, expire);
			}
		}
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("stunners", stunnerList);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 获取FM节目单
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "/getFM", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getFM() {
		List<Map<String, Object>> fmList = fmService.queryListFromDbOrCache(
				SqlUtils.genderQuerySql("man_base_fm",
						"state = 1 order by top_time desc,create_time desc"),
				expire);
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("channels", fmList);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 关注/取消关注用户
	 */
	@Action(value = "/followUser", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String followUser() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-71");
			jsonErrorResponse.setErrorMessage("抱歉，用户id为空");
			return renderJson(jsonErrorResponse);
		}
		if (followUserId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-72");
			jsonErrorResponse.setErrorMessage("抱歉，被关注、取消关注用户id为空");
			return renderJson(jsonErrorResponse);
		}
		if (value == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-73");
			jsonErrorResponse.setErrorMessage("抱歉，是否关注选项不能为空");
			return renderJson(jsonErrorResponse);
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userId", userId);
		paramMap.put("followUserId", followUserId);
		if (value) {
			paramMap.put("type", ManConstants.ATTENTION_TYPE_COMMON);
			paramMap.put("create_time",
					MyDateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss"));
			userAttentionService.add(SqlUtils.genderInsertSql(
					"man_base_user_attention", paramMap));
		} else {
			userAttentionService
					.excute("delete from man_base_user_attention where userId = "
							+ userId + " and followUserId = " + followUserId);
		}
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 上传照片
	 */
	@Action(value = "/uploadPhoto", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String uploadPhoto() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-61");
			jsonErrorResponse.setErrorMessage("抱歉，用户id为空");
			return renderJson(jsonErrorResponse);
		}
		Map<String, Object> user = userService.queryOneRow(SqlUtils
				.genderQuerySql("man_base_user", " id = " + userId));
		if (user == null || user.size() == 0) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-62");
			jsonErrorResponse.setErrorMessage("抱歉，没有该用户的资料");
			return renderJson(jsonErrorResponse);
		}
		byte[] imgByte = null;
		if (StringUtils.isEmpty(fomart)) {
			fomart = "jpg";
		}
		boolean flag = true;
		if (images != null && images.length > 0) {
			for (int i = 0; i < images.length; i++) {
				image = images[i];
				String fileName = new Date().getTime() + "-" + userId + "."
						+ fomart;
				String extPath = "/" + MyDateUtils.parseDateToStr("yyyyMMdd")
						+ "/" + fileName;
				String filePath = SystemConstants.UPLOAD_SERVER_PATH + extPath;
				OutputStream os = null;
				try {
					imgByte = Base64.decode(image);
					File f = new File(filePath);
					// 如果文件不存在或者需要强制覆盖文件，则进行读取并写入
					if (!f.exists()) {
						File p = new File(f.getParent());
						if (!p.exists()) {
							p.mkdirs();
						}
						os = new FileOutputStream(new File(filePath));
						os.write(imgByte);
						Map<String, Object> paramMap = new HashMap<String, Object>();
						paramMap.put("albumId", albumId);
						paramMap.put("userId", userId);
						paramMap.put("summary", summary);
						paramMap.put("imageUrl", SystemConstants.UPLOAD_WEB_URL
								+ extPath);
						albumsImageService.add(SqlUtils.genderInsertSql(
								"man_base_albums_image", paramMap));
					}
				} catch (Exception e) {
					e.printStackTrace();
					JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
					jsonErrorResponse.setErrorCode("-63");
					jsonErrorResponse
							.setErrorMessage("抱歉，base64转换错误，请重新尝试，保存失败");
					return renderJson(jsonErrorResponse);
				} finally {
					try {
						os.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			flag = false;
		}
		if (flag) {
			JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
			return renderJson(jsonSuccessResponse);
		} else {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-64");
			jsonErrorResponse.setErrorMessage("抱歉，更新上传未完全完成，操作失败");
			return renderJson(jsonErrorResponse);
		}
	}

	/**
	 * 上传用户背景图片
	 */
	@Action(value = "/uploadUserBackgroundImage", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String uploadUserBackgroundImage() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-51");
			jsonErrorResponse.setErrorMessage("抱歉，用户id为空");
			return renderJson(jsonErrorResponse);
		}
		Map<String, Object> user = userService.queryOneRow(SqlUtils
				.genderQuerySql("man_base_user", " id = " + userId));
		if (user == null || user.size() == 0) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-52");
			jsonErrorResponse.setErrorMessage("抱歉，没有该用户的资料");
			return renderJson(jsonErrorResponse);
		}
		byte[] imgByte = null;
		if (StringUtils.isEmpty(fomart)) {
			fomart = "jpg";
		}
		String fileName = new Date().getTime() + "-" + userId + "." + fomart;
		String extPath = "/" + MyDateUtils.parseDateToStr("yyyyMMdd") + "/"
				+ fileName;
		String filePath = SystemConstants.UPLOAD_SERVER_PATH + extPath;
		OutputStream os = null;
		try {
			imgByte = Base64.decode(image);
			File f = new File(filePath);
			// 如果文件不存在或者需要强制覆盖文件，则进行读取并写入
			if (!f.exists()) {
				File p = new File(f.getParent());
				if (!p.exists()) {
					p.mkdirs();
				}
				os = new FileOutputStream(new File(filePath));
				os.write(imgByte);
			}
		} catch (Exception e) {
			e.printStackTrace();
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-53");
			jsonErrorResponse.setErrorMessage("抱歉，base64转换错误，请重新尝试，保存失败");
			return renderJson(jsonErrorResponse);
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		boolean flag = userService.update(SqlUtils.genderUpdateSql(
				"man_base_user",
				" id = " + userId,
				"backgroundImageUrl = '" + SystemConstants.UPLOAD_WEB_URL
						+ extPath + "',update_time='"
						+ MyDateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss")
						+ "'"));
		if (flag) {
			JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
			return renderJson(jsonSuccessResponse);
		} else {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-54");
			jsonErrorResponse.setErrorMessage("抱歉，更新图片失败");
			return renderJson(jsonErrorResponse);
		}
	}

	/**
	 * 上传用户头像
	 */
	@Action(value = "/uploadUserImage", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String uploadUserImage() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-51");
			jsonErrorResponse.setErrorMessage("抱歉，用户id为空");
			return renderJson(jsonErrorResponse);
		}
		Map<String, Object> user = userService.queryOneRow(SqlUtils
				.genderQuerySql("man_base_user", " id = " + userId));
		if (user == null || user.size() == 0) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-52");
			jsonErrorResponse.setErrorMessage("抱歉，没有该用户的资料");
			return renderJson(jsonErrorResponse);
		}
		byte[] imgByte = null;
		if (StringUtils.isEmpty(fomart)) {
			fomart = "jpg";
		}
		String fileName = new Date().getTime() + "-" + userId + "." + fomart;
		String extPath = "/" + MyDateUtils.parseDateToStr("yyyyMMdd") + "/"
				+ fileName;
		String filePath = SystemConstants.UPLOAD_SERVER_PATH + extPath;
		OutputStream os = null;
		try {
			imgByte = Base64.decode(image);
			File f = new File(filePath);
			// 如果文件不存在或者需要强制覆盖文件，则进行读取并写入
			if (!f.exists()) {
				File p = new File(f.getParent());
				if (!p.exists()) {
					p.mkdirs();
				}
				os = new FileOutputStream(new File(filePath));
				os.write(imgByte);
			}
		} catch (Exception e) {
			e.printStackTrace();
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-53");
			jsonErrorResponse.setErrorMessage("抱歉，base64转换错误，请重新尝试，保存失败");
			return renderJson(jsonErrorResponse);
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		boolean flag = userService.update(SqlUtils.genderUpdateSql(
				"man_base_user",
				" id = " + userId,
				"imageUrl = '" + SystemConstants.UPLOAD_WEB_URL + extPath
						+ "',update_time='"
						+ MyDateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss")
						+ "'"));
		if (flag) {
			JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
			return renderJson(jsonSuccessResponse);
		} else {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-54");
			jsonErrorResponse.setErrorMessage("抱歉，更新图片失败");
			return renderJson(jsonErrorResponse);
		}
	}

	/**
	 * 获取用户文章
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "/getUserArticle", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getUserArticle() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-41");
			jsonErrorResponse.setErrorMessage("抱歉，用户id为空");
			return renderJson(jsonErrorResponse);
		}
		if (pageNumber < 1) {
			pageNumber = 1;
		}
		if (pageLine < 0) {
			pageLine = ManConstants.COMMON_PAGE_SIZE;
		}
		String sql = "select a.*,u.name from man_base_article a,man_base_user u where a.author_id = "
				+ userId + " and a.author_id = u.id ";
		if (state != null) {
			sql += " and a.state = " + state;
		}
		sql += " order by a.top_time desc,a.create_time desc limit "
				+ ((pageNumber - 1) * pageLine) + "," + pageLine;
		List<Map<String, Object>> articleList = articleService
				.queryListFromDbOrCache(sql, expire);
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("articles", articleList);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 获取用户资料
	 */
	@Action(value = "/getUserInfo", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getUserInfo() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-31");
			jsonErrorResponse.setErrorMessage("抱歉，参数为空，无法查询");
			return renderJson(jsonErrorResponse);
		}
		Map<String, Object> user = userService.queryOneRowFromDbOrCache(
				SqlUtils.genderQuerySql("man_base_user", " id = " + userId),
				expire);
		if (user == null || user.size() == 0) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-32");
			jsonErrorResponse.setErrorMessage("抱歉，没有该用户的资料");
			return renderJson(jsonErrorResponse);
		}
		// 准备用户的相册信息
		List<Map<String, Object>> albumsList = albumsService.queryList(SqlUtils
				.genderQuerySql("man_base_albums", "user_id = " + userId));
		if (albumsList == null) {
			albumsList = new ArrayList<Map<String, Object>>();
		}
		for (int i = 0; i < albumsList.size(); i++) {
			Map<String, Object> albums = albumsList.get(i);
			String albumsId = albums.get("id") + "";
			if (albumsId.trim().length() > 0 && !albumsId.trim().equals("null")) {
				List<Map<String, Object>> albumsImageList = albumsImageService
						.queryList(SqlUtils.genderQuerySql(
								"man_base_albums_image", "albums_id = "
										+ albumsId));
				albums.put("images", albumsImageList);
			}
		}
		user.put("albums", albumsList);
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.setData(user);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 用户登录
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "/login", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String login() {
		if (password == null) {
			password = "";
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("phoneNumber", phoneNumber);
		paramMap.put("platform", platform);
		Map<String, Object> user = userService.queryOneRowFromDbOrCache(
				SqlUtils.genderQuerySql("man_base_user",
						SqlUtils.genderConditionsByType(paramMap, " and ")),
				expire);
		if (user == null || user.size() == 0) {
			// 用户不存在，认为是注册
			paramMap.put("password", password);
			paramMap.put("score", 0);
			paramMap.put("score_state", 0);
			paramMap.put("name", "");
			paramMap.put("imageUrl", "");
			paramMap.put("bwh", "");
			paramMap.put("constellation", "");
			String now = MyDateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss");
			paramMap.put("create_time", now);
			paramMap.put("update_time", now);
			userId = userService.add(SqlUtils.genderInsertSql("man_base_user",
					paramMap));
			user = userService.queryOneRowFromDbOrCache(
					SqlUtils.genderQuerySql("man_base_user", "id = " + userId),
					expire);
		} else {
			if (!(user.get("password") + "").equals(password)) {
				JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
				jsonErrorResponse.setErrorCode("-11");
				jsonErrorResponse.setErrorMessage("抱歉，密码错误");
				return renderJson(jsonErrorResponse);
			}
		}
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.setData(user);
		return renderJson(jsonSuccessResponse);
	}

	/**
	 * 保存用户信息
	 */
	@Action(value = "/saveUser", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String saveUser() {
		if (userId == null) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-1");
			jsonErrorResponse.setErrorMessage("用户id不能为空");
			return renderJson(jsonErrorResponse);
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(name)) {
			paramMap.put("name", name);
		}
		if (gender != null) {
			paramMap.put("gender", gender);
		}
		if (age != null) {
			paramMap.put("age", age);
		}
		if (!StringUtils.isEmpty(bwh)) {
			paramMap.put("bwh", bwh);
		}
		if (!StringUtils.isEmpty(constellation)) {
			paramMap.put("constellation", constellation);
		}
		if (paramMap.size() == 0) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-2");
			jsonErrorResponse
					.setErrorMessage("请检查参数，可能没有传入需要修改的选项信息内容，或者传入的值不符合相关类型");
			return renderJson(jsonErrorResponse);
		}
		boolean flag = userService.update(SqlUtils.genderUpdateSql(
				"man_base_user", "id = " + userId,
				SqlUtils.genderConditionsByType(paramMap, ",")));
		if (flag) {
			JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
			return renderJson(jsonSuccessResponse);
		} else {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-2");
			jsonErrorResponse.setErrorMessage("更新失败");
			return renderJson(jsonErrorResponse);
		}
	}

	/**
	 * 获取启动广告
	 * 
	 * @return { success: true data: { imageUrl: string //图片网址 } }
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "/getSplashImage", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String getSplashImage() {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("is_used", 0);
		String key = "getSplashImage";
		Map<String, Object> img = (Map<String, Object>) Cache.get(key);
		if (img == null) {
			img = splashScreenService.queryOneRow(SqlUtils.genderQuerySql(
					"man_base_splashscreen",
					SqlUtils.genderConditionsByType(paramMap, " and ")
							+ " order by create_time desc"));
			if (img != null) {
				Cache.add(key, img, expire);
			}
		}
		if (img == null || img.size() == 0) {
			JsonErrorResponse jsonErrorResponse = new JsonErrorResponse();
			jsonErrorResponse.setErrorCode("-21");
			jsonErrorResponse.setErrorMessage("未能找到闪屏的图片信息");
			return renderJson(jsonErrorResponse);
		}
		JsonSuccessResponse jsonSuccessResponse = new JsonSuccessResponse();
		jsonSuccessResponse.getData().put("imageUrl", img.get("logo"));
		return renderJson(jsonSuccessResponse);
	}
	
	/**
	 * 登陆
	 */
	@Action(value = "/viewLogin", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String viewLogin() {
		return dispatcher("/login.jsp");
	}

	/**
	 * 退出
	 */
	@Action(value = "/loginOut", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String loginOut() {
		getSession().removeAttribute(SystemConstants.USER_SESSION_KEY);
		return chain("/user/viewLogin");
	}

	/**
	 * 登陆
	 */
	@Action(value = "/loginIn", interceptorRefs = @InterceptorRef("withoutAuthStack"))
	public String loginIn() {
		if (StringUtils.isEmpty(passport)) {
			getRequest().setAttribute("errorCode", "1");
			getRequest().setAttribute("msg", "用户名不能为空");
			return dispatcher("/login.jsp");
		}
		if (StringUtils.isEmpty(password)) {
			getRequest().setAttribute("errorCode", "2");
			getRequest().setAttribute("msg", "密码不能为空");
			getRequest().setAttribute("passport", passport);
			return dispatcher("/login.jsp");
		}
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("passport", passport);
		paramMap.put("pwd", password);
		logger.debug(paramMap);
		Map<String, Object> user = userService.queryOneRow(SqlUtils
				.genderQuerySql("man_base_user",
						SqlUtils.genderConditionsByType(paramMap, " and ")));
		if (user != null && user.size() > 0) {
			getRequest().getSession().setAttribute(
					SystemConstants.USER_SESSION_KEY, user);
			if (!(user.get("state") + "").equals("1")) {
				getRequest().setAttribute("errorCode", "4");
				getRequest().setAttribute("passport", passport);
				getRequest().setAttribute("msg", "账户状态异常，可能已被禁用，请联系管理员");
				return dispatcher("/login.jsp");
			}
			// TODO 可以在这里根据用户的类型决定跳转地址，或者到前台，在jsp中判断也可以，这两者登陆后应该是有区别的
			return dispatcher("/user/index.action");
		}
		getRequest().setAttribute("errorCode", "3");
		getRequest().setAttribute("passport", passport);
		getRequest().setAttribute("msg", "用户名或密码错误");
		return dispatcher("/login.jsp");
	}

	/**
	 * 首页
	 */
	@SuppressWarnings("unchecked")
	@Action(value = "/index", interceptorRefs = @InterceptorRef("withAuthStack"))
	public String index() {
		Map<String, Object> user = (Map<String, Object>) getRequest()
				.getSession().getAttribute(SystemConstants.USER_SESSION_KEY);
		if (user != null && user.size() > 0) {
		}
		return dispatcher("/indexs.jsp");
	}

	public void setParamMap(Map<String, Object> paramMap) {
		this.paramMap = paramMap;
	}

	public void setPassport(String passport) {
		this.passport = passport;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setGender(Integer gender) {
		this.gender = gender;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public void setBwh(String bwh) {
		this.bwh = bwh;
	}

	public void setConstellation(String constellation) {
		this.constellation = constellation;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setPlatform(String platform) {
		this.platform = platform;
	}

	public void setPageNumber(Integer pageNumber) {
		this.pageNumber = pageNumber;
	}

	public void setPageLine(Integer pageLine) {
		this.pageLine = pageLine;
	}

	public void setState(Integer state) {
		this.state = state;
	}

	public void setImage(String image) {
		this.image = image;
	}

	public void setFomart(String fomart) {
		this.fomart = fomart;
	}

	public void setImages(String[] images) {
		this.images = images;
	}

	public void setAlbumId(Long albumId) {
		this.albumId = albumId;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	public void setFollowUserId(Long followUserId) {
		this.followUserId = followUserId;
	}

	public void setValue(Boolean value) {
		this.value = value;
	}

	public void setColumnId(Long columnId) {
		this.columnId = columnId;
	}

	public void setArticleId(Long articleId) {
		this.articleId = articleId;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public void setQuestionId(Long questionId) {
		this.questionId = questionId;
	}

}
